/*
  This program sets the default values of all the structures used in the modeling simulation
  An accurate description of all the variables purpouse can be found in ssm.h
  The defaults are written out to simulation.str, race.str, dynamic.str, car.str, and weather.str
  This program must be ran before the actual modeling program is ran.

  Later revisions of this modeling program may implement controlSet and thus this program
  would need to set the defaults of that structure
*/

#include <stdio.h>
#include "ssm.h"
#include "ssm_conversions.h"

int eatComment(FILE *);

int main(int argc, char *argv[])
{
	FILE *file;

	if((file=fopen("structs.default","r"))==NULL)
	{
		fprintf(stderr,"ERROR: Could not open structs.default");
	}
	

	Simulation sim;
	Race race;
	Dynamic dynamic;
	Car car;
	Weather weather;
	
	eatComment(file);
	if(fscanf(file, "%lf	%lf	%d	%d	%lf\n", &sim.dt, &sim.t, &sim.imax, &sim.iprint, &sim.stoptime)!=5)
	{
		fprintf(stderr,"ERROR: reading simulation data\n");	
		return -1;
	}

	writeSim("sim.str", &sim);

	eatComment(file);
	if (fscanf(file,"%lf	%lf\n", &race.time_start, &race.time_stop)!=2)
 	{
		fprintf(stderr,"ERROR: reading race start and end times\n");
		return -1;
	}

	race.time_start = race.time_start * HTOS;
	race.time_stop  = race.time_stop  * HTOS;
	writeRace("race.str", &race); 
	
	eatComment(file);
	if(fscanf(file,"%lf	%lf	%lf	%lf	%lf	%lf	%lf	%lf	%lf	%lf	%lf	%lf	%lf\n",
		&car.A, &car.C_d, &car.C_rr, &car.W, &car.M, &car.P_arrayMax, 
		&car.M_d, &car.M_r, &car.P_p, &car.B_CHeff, &car.B_n, &car.accR, &car.decelR)!=13)
	{
		fprintf(stderr,"ERROR: reading car data\n");
		return -1;
	}

	writeCar("car.str", &car);
	
	eatComment(file);
	if(fscanf(file,"%lf	%lf\n",&dynamic.distance, &dynamic.B_charge)!=2)
	{
		fprintf(stderr,"ERROR: reading dynamic settings\n");
		return -1;	
	}

	writeDynamic("dynamic.str", &dynamic);

	eatComment(file);
	if(fscanf(file,"%lf	%lf	%lf	%lf	%lf	%lf	%lf\n", 
			&weather.rho, &weather.sun_rise, &weather.sun_length,
			&weather.phi_n, &weather.winds, &weather.windd, &weather.CloudCover)!=7)
	{
		fprintf(stderr,"ERROR: reading weather information\n");
	}

	weather.sun_rise   = weather.sun_rise   * HTOS;
	weather.sun_length = weather.sun_length * HTOS;
	weather.phi_n      = weather.phi_n      * DEGTORAD;
	weather.windd      = weather.windd      * DEGTORAD;

	writeWeather("weather.str", &weather);

	return 0;
}

int eatComment(FILE *fp)
{
	char line[1024];
	char c;
	while(1)
	{
		if((c=fgetc(fp))=='#')
			fgets(line,1024,fp);
		else
			if(ungetc(c,fp)!=c)
				return (-1);
			else
				return 0;
	}
			
}

